<template>
  <div class="cb-main-container">
    <div class="search-box">
      <el-form :model="searchFormConfig.model" ref="searchFormRef" inline>
        <el-form-item label="名称" prop="name">
          <el-input v-model="searchFormConfig.model.name" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="searchFormConfig.model.status" placeholder="请选择产品状态" style="width: 168px">
            <el-option v-for="(item, index) in statusEnum" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button icon="refresh" @click="onReset">重置</el-button>
          <el-button icon="search" type="primary" @click="onSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="main-content">
      <div class="operation-box">
        <el-button icon="plus" type="primary" @click="onAdd">新增</el-button>
      </div>
      <div class="table-box">
        <el-table :data="tableConfig.data" size="large" empty-text="暂无数据">
          <el-table-column type="index" width="50" />
          <el-table-column property="name" label="名称"/>
          <el-table-column property="categoryName" label="分类" />
          <el-table-column property="costPrice" label="成本价(元)" />
          <el-table-column property="sellingPrice" label="销售价(元)" />
          <el-table-column property="safeStockQuantity" label="安全库存" />
          <el-table-column label="状态">
            <template #default="scope">
              <el-tag :type="(scope.row.status === 1) ? 'primary' : 'info'">{{ scope.row.status === 1 ? '启用' : '禁用' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column property="specifications" label="规格" show-overflow-tooltip/>
          <el-table-column label="操作" align="right" width="160">
            <template #default="scope">
              <el-button link type="primary" icon="edit" @click="onEdit(scope.row)">编辑</el-button>
              <el-button link type="danger" icon="delete">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-box">
        <el-pagination background layout="prev, pager, next" :total="searchFormConfig.model.total" @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- 添加/编辑 -->
    <el-drawer v-model="drawerConfig.visible" size="35%" :title="drawerConfig.title" :close-on-click-modal="false" @close="drawerCloseHandle">
      <div class="cb-drawer-container">
        <div class="cb-main">
          <el-form :model="formConfig.model" :label-width="formConfig.labelWidth" ref="formRef">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="编码" prop="code">
                  <el-input v-model="formConfig.model.code" disabled readonly placeholder="系统自动生成" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="名称" prop="name">
                  <el-input v-model="formConfig.model.name" maxlength="32" placeholder="请填写产品名称" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="分类" prop="categoryId">
                  <el-tree-select
                      check-strictly
                      v-model="formConfig.model.categoryId"
                      :data="formConfig.categoryTree"
                      :props="formConfig.categoryTreeSelectProps"
                      node-key="id"
                      no-data-text="暂无数据"
                      placeholder="请选择所属分类"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="品牌" prop="brandId">
                  <el-select v-model="formConfig.model.brandId" placeholder="请选择所属品牌" no-data-text="暂无数据" filterable>
                    <el-option v-for="(item, index) in formConfig.brandData" :key="index" :value="item.id" :label="item.name" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="规格" prop="specifications">
                  <el-input v-model="formConfig.model.specifications" maxlength="255" placeholder="请填写产品规格" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                  <el-form-item label="单位" prop="unitId">
                    <el-select filterable v-model="formConfig.model.unitId" placeholder="请选择单位" no-data-text="暂无数据">
                      <el-option v-for="(item, index) in formConfig.unitData" :key="index" :label="item.name" :value="item.id" />
                    </el-select>
                  </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item prop="costPrice" label="成本单价(元)">
                  <el-input v-model="formConfig.model.costPrice" placeholder="请输入成本单价/元" maxlength="16">
                    <template #append>元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="sellingPrice" label="售价单价(元)">
                  <el-input v-model="formConfig.model.sellingPrice" placeholder="请输入销售单价/元" maxlength="16">
                    <template #append>元</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item prop="inputTaxRate" label="进项税率(%)">
                  <el-input v-model="formConfig.model.inputTaxRate" placeholder="请输入进项税率" maxlength="16">
                    <template #append>%</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="outputTaxRate" label="销项税率(%)">
                  <el-input v-model="formConfig.model.outputTaxRate" placeholder="请输入销项税率" maxlength="16" >
                    <template #append>%</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="安全库存" prop="safeStockQuantity">
                  <el-input v-model="formConfig.model.safeStockQuantity" placeholder="请输入安全库存数量" maxlength="8"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item prop="image" label="产品图片">
              <el-upload
                  class="avatar-uploader"
                  action=""
                  :show-file-list="false"
                  :before-upload="beforeUploadHandle"
                  :http-request="httpRequestHandle">
                <img v-if="formConfig.model.image" :src="formConfig.model.image" class="avatar"  alt=""/>
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
        <div class="cb-footer">
          <el-button type="info" @click="onDrawerCancel">取消</el-button>
          <el-button type="primary" @click="onDrawerConfirm">确认</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from "vue"
import { add, edit, pageList, treeCategory, brandList, unitSelectList } from '@/api/erp/product.js'
import { clear } from '@/util/ObjectUtil.js'
import { upload } from '@/api/common/file.js'
import {ElMessage} from "element-plus"
import { isImageFile } from '@/util/FileUtil.js'

defineOptions({
  name: '/erp/productManagement/product'
})

const statusEnum = [
  {label: '禁用', value: 0},
  {label: '启用', value: 1}
]

const searchFormRef = ref(null)
const searchFormConfig = reactive( {
  model: {
    name: '',
    status: '',
    pageNum: 1,
    pageSize: 10,
    total: 0,
  }
})

const drawerConfig = reactive({
  visible: false,
  title: '新增',
  size: '35%'
})

const formRef = ref(null)
const formConfig = reactive({
  labelWidth: 96,
  model: {
    id: '',
    code: '',
    name: '',
    categoryId: '',
    brandId: '',
    image: '',
    specifications: '',
    description: '',
    unitId: '',
    safeStockQuantity: 0,
    status: 1,
    costPrice: '',
    sellingPrice: '',
    inputTaxRate: '',
    outputTaxRate: ''
  },
  categoryTree: [],
  brandData: [],
  unitData: [],
  categoryTreeSelectProps: {
    label: 'name'
  }
})

const tableConfig = reactive({
  data: [
    {id: 1, name: '测试产品', shortName: 'aaa', status: 1,remarks: '测试' },
    {id: 2, name: '测试产品11', shortName: 'bbb', status: 2,  remarks: '测试'},
  ]
})

const onAdd = () => {
  treeCategory().then(resp => {
    formConfig.categoryTree = resp.data
  })

  brandList().then(resp => {
    formConfig.brandData = resp.data
  })

  unitSelectList().then(resp => {
    formConfig.unitData = resp.data
  })

  drawerConfig.visible = true
}
const handleCurrentChange =(currentPage) => {
  searchFormConfig.model.pageNum= currentPage
}

const onEdit = async (rowData) => {
  // 并行请所有的数据
  try {
    const [categoryResp, brandResp, unitResp] = await Promise.all([
      treeCategory(),
      brandList(),
      unitSelectList()
    ])

    formConfig.categoryTree = categoryResp ? categoryResp.data : []
    formConfig.brandData = brandResp ? brandResp.data : []
    formConfig.unitData = unitResp ? unitResp.data : []

    formConfig.model = {...rowData}
    drawerConfig.visible = true
  } catch (error) {
    ElMessage.error("加载数据失败，请稍后再试")
  }
}

const onReset = () => {
  searchFormConfig.model.pageNum = 1
  if (!searchFormRef.value) return
  searchFormRef.value.resetFields()
  requestPageList()
}

const onSearch = () => {
  searchFormConfig.model.pageNum = 1
  requestPageList()
}

const onDrawerCancel = () => {
  drawerConfig.visible = false
}

const onDrawerConfirm = async () => {
  const valid = await formRef.value.validate()
  if (valid) {
    if (formConfig.model.id) {
      await edit(formConfig.model)
    } else {
      await add(formConfig.model)
    }

    drawerConfig.visible = false
  }
}

const drawerCloseHandle = () => {
  formRef.value.resetFields()
  clear(formConfig.model)

  requestPageList()
}

const beforeUploadHandle = (rawFile) => {
  if(!isImageFile(rawFile)) {
    ElMessage.error('产品图片仅支持JPG格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('产品图片大小不能超过2MB!')
    return false
  }
  return true
}

const httpRequestHandle = (options) => {
  upload(options['file']).then(resp => {
    formConfig.model.image = resp.data.path
  })
}

const requestPageList = () => {
  pageList(searchFormConfig.model).then(resp => {
    tableConfig.data = resp.data.data
    searchFormConfig.model.total = Number.parseInt(resp.data.total)
  })
}

onMounted(() => {
  requestPageList()
})
</script>

<style scoped lang="scss">
.cb-main-container {
  display: flex;
  flex-direction: column;

  .search-box {
    @include containerStyle;
    padding-bottom: 0;
  }

  .main-content {
    flex: 2;
    @include containerStyle;

    display: flex;
    flex-direction: column;

    .table-box {
      flex: 2;
      margin-bottom: $cb_margin-value;
    }
  }

  .cb-drawer-container {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;

    .cb-main {
      flex-grow: 2;
    }

    .cb-footer {
      width: 100%;
      height: 26px;
      margin-top: $cb-margin-sm;
      text-align: right;
    }
  }

  .avatar-uploader {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }

  :deep(.avatar-uploader .el-upload) {
    border: 1px dashed $cb-border-color;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: .2s;
  }

  :deep(.avatar-uploader .el-upload:hover) {
    border-color: $cb-color-primary;
  }

  :deep(.el-icon.avatar-uploader-icon) {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
}
</style>
